<template>
  <div class="company">
    <template v-if="!ifEmployee">
      <a-row>
        <a-col>
          <h3>
            <IdcardOutlined />
            <span style="margin-left: 8px;">{{ $t("职位") }}</span>
          </h3>
        </a-col>
      </a-row>
      <a-row style="margin-top: 16px;">
        <a-col :span="16" style="display: flex;">
          <a-button style="font-size: 12px;" v-permission="['createFlag']" @click="onAddClick"><i class="fa fa-plus" /><span  style="margin-left: 4px;margin-right: 4px;">{{ $t("add") }}</span></a-button>
          <a-button style="margin-left: 8px; margin-right: 8px; font-size: 12px;" @click="refreshList"><i class="fa fa-sync" /><span  style="margin-left: 4px;margin-right: 4px;">{{ $t("refresh") }}</span></a-button>
          
          <div style="margin-left: 8px; margin-right: 8px; width: 500px;">
            <span style="font-size: 12px;">{{ $t('岗位类型') }} :</span>
            <a-select :getPopupContainer="(triggerNode: any) => triggerNode.parentNode" ref="select" v-model:value="positionTypeVule" @change="positionTypechange" style="width: 70%;">
              <a-select-option v-for="(item, index) in positionTypeList" :value="item.dictData">{{ isCn ? item.descZh
                :
                isArabic ? item.descAr : item.dictDesc}}</a-select-option>
            </a-select>
          </div>
          
          <a-input-group compact>
            <a-input v-model:value="queryParam.keyword"  style="width: 30%;" :placeholder="`${$t('search')}...`" allowClear @pressEnter="onSearch"/>
            <a-button type="" class="search" @click="onSearch"><i class="fa fa-search-plus" /><span style="margin-left: 4px;margin-right: 4px;">{{ $t('search') }}</span></a-button>
          </a-input-group>
        </a-col>
        <a-col :span="8" style="display: flex;justify-content: flex-end;align-items: center;">
          <span>{{ $t("公司") }}:</span>
          <span style="color: #ff6700;margin: 0 8px;"> {{ companyName }}</span>
          <a-dropdown>
            <i class="fa fa fa-angle-down fa-2x" @click.prevent />
            <template #overlay>
              <a-menu class="menu-list">
                <a-menu-item v-for="(item, index) in menuList" @click="onSwitch(item.id)">{{ item.name }}</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-col>
      </a-row>
      <Table
        ref="Tabular"
        :tableDatas="dataSource"
        :loading="loading"
        :pages="pages"
        :total="total"
        :columns="columns"
        :conf="tabConf"
        :is2Pagenation="true"
        @search="handleSearch"
        @delete="handleDelete"
        @editor="handleUpdate"
        :scrollParams="{ x: addRowWidthALl }"
      >
        <template #category="{ row, index }">
          <span>{{ getListName(row.category, categoryList, 'category') || '-' }}</span>
        </template>
        <template #buName="{ row, index }">
          <span :title="isCn ? row.buNameZh : isArabic ? row.buNameAr : row.buName">{{ isCn ? row.buNameZh : isArabic ? row.buNameAr : row.buName }}</span>
        </template>
        <template #levelId="{ row, index }">
          <span>{{ getListName(row.levelId, levelList, 'levelId') || '-' }}</span>
        </template>
        <template #personalType="{ row, index }">
          <span>{{ getListName(row.personalType, positionPersonalTypeList, 'personalType') || '-' }}</span>
        </template>
        <template #positionType="{ row, index }">
          <span>{{ getListName(row.positionType, positionTypeList, 'positionType') || '-' }}</span>
        </template>
        <template #salaryRate="{ row, index }">
          <span>{{ getListName(row.salaryRate, salaryRateList, 'salaryRate') || '-' }}</span>
        </template>
        <template #employeeCount="{ row, index }">
          <a @click="employeeClick(row)">{{ row.employeeCount || '' }}</a>
        </template>
        <template #salaryAmount="{ row, index }">
          {{ formatNumber(row.salaryAmount) }}
        </template>
      </Table>
    </template>
    <template v-if="ifEmployee">
      <div style="display: flex;justify-content: flex-end;cursor: pointer;" @click="closeEmployee"><i class="fa fa-times" /></div>
      <positionEmployee  ref="employeeModalRed" :companyId="companyId" :positionData="positionData"/>
    </template>

    <positionModal
      ref="positionModalRef"
      :companyId="companyId"
      @refreshList="refreshList"
      :levelList="levelList"
      :categoryList="categoryList"
      :positionPersonalTypeList="positionPersonalTypeList"
      :positionTypeList="positionTypeSelectList"
      :rotationList="rotationList"
      :salaryRateList="salaryRateList"/>
    <positionDetailsModal
      ref="positionDetailsModalRef"
      :companyId="companyId"
      :levelList="levelList"
      :categoryList="categoryList"
      :positionPersonalTypeList="positionPersonalTypeList"
      :positionTypeList="positionTypeList"
      :rotationList="rotationList"
      :salaryRateList="salaryRateList"/>
  </div>
</template>
<script setup lang="ts">
  import { h } from 'vue';
  import Table from "@/components/Table/index.vue";
  import positionEmployee from '@/pages/staff/staffPage/components/position/positionDetailTable.vue'
  import { reactive, ref, watch, onMounted, nextTick, getCurrentInstance } from "vue";
  import { IdcardOutlined, EyeOutlined } from '@ant-design/icons-vue';
  import positionModal from './components/position-modal.vue'
  import positionDetailsModal from './components/position-details-modal.vue'
  import { Modal, message } from 'ant-design-vue';
  import { GetEnterpriseList, GetPositionPage, DeletePosition } from "@/api/organization/index";
  import { GetBatchCodeDict } from "@/api/public"
  import hooks, { employeeStore } from "@/hooks/index";
  import { useI18n } from 'vue-i18n';
  import { useLanguage } from "@/hooks/index";
  const { isEn, isCn, isArabic } = useLanguage();
  const { t: $t } = useI18n();
  const loading = ref(false)
  const dataSource = ref([])
  const ifEmployee = ref(false)
  const columns = [
    {
      title: () => {
        return (
          $t('唯一编码')
        )
      },
      dataIndex: 'uniqueCode',
      key: 'uniqueCode',
      align: 'left',
      width: 200,
      ellipsis: true
    },
    {
      title: () => {
        return (
          $t('positionTitle')
        )
      },
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('缩写')
        )
      },
      dataIndex: 'shortName',
      key: 'shortName',
      width: 200,
      ellipsis: true,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('类别')
        )
      },
      dataIndex: 'category',
      key: 'category',
      slot: "category",
      width: 120,
      align: 'center'
    },
   
    {
      title: () => {
        return (
          $t('汇报')
        )
      },
      dataIndex: 'reportToName',
      key: 'reportToName',
      ellipsis: true,
      width: 150,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('组织')
        )
      },
      dataIndex: 'buName',
      key: 'buName',
      slot: "buName",
      ellipsis: true,
      width: 150,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('岗位类型')
        )
      },
      dataIndex: 'positionType',
      key: 'positionType',
      slot: "positionType",
      width: 120,
      align: 'center'
    },
    {
      title: () => {
        return (
          $t('岗位人员类型')
        )
      },
      dataIndex: 'personalType',
      key: 'personalType',
      slot: "personalType",
      width: 160,
      align: 'center'
    },
    {
      title: () => {
        return (
          $t('人数')
        )
      },
      dataIndex: 'headCount',
      key: 'headCount',
      width: 100,
      align: 'center'
    },
    {
      title: () => {
        return (
          $t('倒班')
        )
      },
      dataIndex: 'rotation',
      key: 'rotation',
      slot: "rotation",
      width: 120,
      align: 'center'
    },
    {
      title: () => {
        return (
          $t('薪酬水平')
        )
      },
      dataIndex: 'salaryAmount',
      key: 'salaryAmount',
      slot: "salaryAmount",
      width: 150,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('薪酬费率')
        )
      },
      dataIndex: 'salaryRate',
      key: 'salaryRate',
      slot: "salaryRate",
      width: 100,
      align: 'center'
    },
    {
      title: () => {
        return (
          $t('关联岗位名称')
        )
      },
      dataIndex: 'relatedName',
      key: 'relatedName',
      ellipsis: true,
      width: 160,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('描述')
        )
      },
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 200,
      align: 'left'
    },
    {
      title: () => {
        return (
          $t('员工数量')
        )
      },
      dataIndex: 'employeeCount',
      key: 'employeeCount',
      slot: "employeeCount",
      width: 120,
      align: 'center'
    },
    {
      title: '',
      dataIndex: 'operation',
      key: 'operation',
      slot: "opt",
      edit: true,
      delete: true,
      fixed: 'right',
      width: 120,
      align: 'left'
    }
  ]

  let addRowWidthALl = ref(0);
  columns &&
    columns.forEach((w: any) => {
      addRowWidthALl.value += w.width;
    });
  let queryParam = ref({
    keyword: ''
  })
  let pages = ref<object>({ pageSize: 30, pageNo: 1 });
  let total = ref(20);
  onMounted(() => {
    getMenuList()
    getPositionCode()
    getCode()
  })
  const menuList = ref([])
  const companyId = ref(null)
  const companyName = ref(null)
  let Tabular = ref(null);
  const getMenuList = () => {
    GetEnterpriseList().then(res => {
      if (res.code !== 200) return
      menuList.value = res.data
      companyId.value = menuList.value[0].id
      companyName.value = `${menuList.value[0].shortName}-${menuList.value[0].name}`
      getPageList(menuList.value[0].id)
    })
  }
  // 公司切换
  const onSwitch = (id) => {
    let companyObj = menuList.value.find(item => item.id === id)
    companyId.value = id
    companyName.value = `${companyObj.shortName}-${companyObj.name}`
    getPageList(id)
  }
  const formatNumber = (number) => {
    if (number) {
      return number.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    }
  }
  const positionTypeVule = ref('1')
  const positionTypechange = (val: any) => {
    positionTypeVule.value = val
    getPageList(companyId.value)
  }
  const handleSearch = ({searchForm, pager }) => {
    console.log('sss', pager)
    pages.value.pageSize = pager.pageSize;
    pages.value.pageNo = pager.pageNo;
    getPageList()
  }
  const getPageList = (id) => {
    loading.value = true
    GetPositionPage({
      ...pages.value,
      keyword: queryParam.value.keyword,
      enterpriseId: id || companyId.value,
      positionType: Number(positionTypeVule.value)
    }).then(res => {
      if (res.code !== 200) return
      dataSource.value = res.data
      total.value = res.totalCount;
      pages.value.pageSize = res.pageSize;
      pages.value.pageNo = res.pageNo;
    }).finally(() => {
      loading.value = false
    });
  }
  const handleFlush = () => {
    Tabular.value.flush();
  };
  
  const refreshList = () => {
    handleFlush()
  }
  const handleDelete = (record: any) => {
    DeletePosition({
      uuid: record.uuid
    }).then(res => {
      message.success($t('操作成功'));
      handleFlush()
    })
  }
  const onSearch = debounce((evt) => {
    const fn = (evt) => {
      pages.value.pageSize = 30;
      pages.value.pageNo = 1;
      getPageList()
    }
    fn(evt)
  }, 1000)
  const positionModalRef = ref(null)
  const onAddClick = () => {
    if (positionModalRef.value) positionModalRef.value.showModal(companyId.value)
  }
  const handleUpdate = (record: {}) => {
    if (positionModalRef.value) positionModalRef.value.showModal(companyId.value, record)
  }
  const levelList = ref([])
  const categoryList = ref([])
  const positionPersonalTypeList = ref([])
  const positionTypeList = ref([])
  const rotationList = ref([])
  const salaryRateList = ref([])
  const getCode = () => {
    GetBatchCodeDict({
      dictKey: 'positionLevel,positionCategory,positionPersonalType,positionType,employeeRotationDesc,positionSalaryRate'
    }).then(res => {
      if (res.code !== 200) return
      levelList.value = res.data.positionLevel
      categoryList.value = res.data.positionCategory
      positionPersonalTypeList.value = res.data.positionPersonalType
      positionTypeList.value = res.data.positionType
      rotationList.value = res.data.employeeRotationDesc
      salaryRateList.value = res.data.positionSalaryRate
    })
  }

  const positionTypeSelectList = ref([]);
  const getPositionCode = () => {
    GetBatchCodeDict({
      dictKey: "positionType",
      hidden: true
    }).then((res) => {
      if (res.code !== 200) return;
      positionTypeSelectList.value = res.data.positionType;
    });
  };

const getListName = (val, codeValue, codeName) => {
  let name = null;
  let obj = null;
  if (val || val === 0) {
    obj = codeValue.find((item) => {
      if (item.dictData == String(val)) return item;
    });
    if (codeName == 'levelId') {
      name = isCn.value ? `${obj?.dictData} - ${obj?.descZh}` : isArabic.value ? `${obj?.dictData} - ${obj?.descAr}` : `${obj?.dictData} - ${obj?.dictDesc}`;
    } else {
      name = isCn.value ? obj?.descZh : isArabic.value ? obj?.descAr : obj?.dictDesc;
    }
  }
  return name;
};
const positionDetailsModalRef = ref(null)
const rowClick = (record: any, index: number) => {
  return {
    onClick: (event: any) => {
      if (event.target.cellIndex < 6) {
        if (positionDetailsModalRef.value) positionDetailsModalRef.value.showModal(record)
      } 
    },
  };
}
const tabConf = {
  customRow: rowClick
}

const positionData = ref(null)
const employeeClick = (row: any) => {
  if (row.employeeCount === 0) return
  ifEmployee.value = true
  positionData.value = row // 职位id
  employeeStore.useEmployeeHook.buid = row.buId
  employeeStore.useEmployeeHook.closeStatus = true
}
const closeEmployee = () => {
  ifEmployee.value = false
}
</script>
<style lang="scss" scoped>
  .company {
    padding: 24px 24px 0 16px;
  }
  .fa-angle-down {
    color: #a7b1c2;
  }
  .menu-list {
    max-height: 500px;
    overflow-y: scroll;
    min-width: 100px;
    text-align: left;
    &::-webkit-scrollbar {
      display: none
    }
  }
  .search {
    height: 32.86px;
    background-color: #fff;
    color: #676a6c;
    border: 1px solid #d9d9d9;
    border-radius: 0 3px 3px 0;
  }
  ::v-deep {
    // 全局样式修改回来
    .ant-input-affix-wrapper {
      border: 1px solid #dadada !important;
      height: 100%;
    }
    .ant-input:hover,
    .ant-input {
      border-bottom: none !important;
    }
    .ant-input-affix-wrapper >input.ant-input {
      padding: 4px 11px;
    }
    .ant-input-affix-wrapper:not(.ant-input-affix-wrapper-disabled):hover {
      border-color: var(--btn-bg-save) !important;
    }
    .ant-input-affix-wrapper-focused,
    .ant-input-affix-wrapper:hover,
    .ant-input-affix-wrapper:focus {
      border-color: var(--btn-bg-save) !important;
    }
    .ant-input-affix-wrapper:focus {
      border: 1px solid #d9d9d9 !important;
    }
    .ant-input-affix-wrapper:hover {
      border: 1px solid #d9d9d9 !important;
    }
    .ant-input-affix-wrapper .ant-input-suffix {
      padding-right: 4px;
    }
    .ant-input-group.ant-input-group-compact>*:first-child {
      border-start-start-radius: 3px;
      border-end-start-radius: 3px;
    }
    .ant-input-group.ant-input-group-compact>*:last-child {
      border-start-end-radius: 3px;
      border-end-end-radius: 3px;
    }
  }
</style>
  